﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace EquipmentConfig.Class
{
    public class Common
    {
        /// <summary>
        /// 用户类型
        /// </summary>
        public static object[] UserInfo = new object[] { "管理员", "超级管理员" };

        /// <summary>
        /// 检查IP地址
        /// </summary>
        /// <param name="strIP">IP</param>
        /// <returns>true,false</returns>
        public static bool CheckIP(string strIP)
        {
            return Regex.IsMatch(strIP, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }

        /// <summary>
        /// 生成图片文件
        /// </summary>
        /// <param name="strStationNo">站点编号</param>
        /// <param name="byteImage">文件字节</param>
        /// <returns></returns>
        public static bool CreateImageFile(string strPath, byte[] byteImage)
        {
            try
            {
                string strValue = Path.GetDirectoryName(strPath);
                if (!Directory.Exists(strValue))
                {
                    Directory.CreateDirectory(strValue);
                }
                
                FileStream fs = new FileStream(strPath, FileMode.Create, FileAccess.ReadWrite);
                fs.Write(byteImage, 0, byteImage.Length);
                fs.Flush();
                fs.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 清理目录下2天前文件
        /// </summary>
        public static void ClearFile(string strFilePath)
        {
            if (Directory.Exists(strFilePath))
            {
                string[] strDirectories = Directory.GetFiles(strFilePath);
                for (int intLoop = 0; intLoop < strDirectories.Length; intLoop++)
                {
                    FileInfo fi = new FileInfo(strDirectories[intLoop]);
                    TimeSpan d = DateTime.Now - fi.CreationTime;
                    if (d.Days > 2)
                    {
                        if (File.Exists(strDirectories[intLoop]))
                        {
                            File.Delete(strDirectories[intLoop]);
                        }
                    }
                }
            }
        }

        /// <summary>
        ///检查网络连接
        /// </summary>
        /// <param name="strIP">IP</param>
        /// <returns>true,false</returns>
        public static bool CheckClient(string strIP)
        {
            Ping ping = new Ping();
            PingReply pingReply = ping.Send(strIP);
            if (pingReply.Status == IPStatus.Success)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 两字节转int
        /// </summary>
        /// <param name="b1"></param>
        /// <param name="b2"></param>
        /// <returns></returns>
        public static int BytesToShort(byte b1, byte b2)
        {
            return b1 << 8 | b2;
        }

        /// <summary>
        /// 取整数的某一位
        /// </summary>
        /// <param name="resource">要取某一位的整数</param>
        /// <param name="mask">要取的位置索引，自右至左为0-7</param>
        /// <returns>返回某一位的值（0或者1）</returns>
        public static int GetIntBit(int resource, int mask)
        {
            return resource >> mask & 1;
        }

        public static string ConvertDataBySpace(Byte[] data)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                foreach (Byte b in data)
                {
                    sb.Append(Convert.ToString(b, 16).ToUpper().PadLeft(2, '0') + " ");
                }
                return sb.ToString().Trim();
            }
            catch { return string.Empty; }
        }

        /// <summary>
        /// 16进制原码字符串转字节数组
        /// </summary>
        /// <param name="hexString">"AABBCC"或"AA BB CC"格式的字符串</param>
        /// <returns></returns>
        public static byte[] ConvertHexStringToBytes(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if (hexString.Length % 2 != 0)
            {
                throw new ArgumentException("参数长度不正确");
            }

            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
            {
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            }

            return returnBytes;
        }

        public static byte[] GetByteForString(string strText, int intMaxCount)
        {
            byte[] bytes = new byte[intMaxCount];
            byte[] byteText = System.Text.Encoding.Default.GetBytes(strText);
            if (bytes.Length >= byteText.Length)
            {
                Array.Copy(byteText, 0, bytes, 0, byteText.Length);
            }
            return bytes;
        }

        /// <summary>
        /// 读取文件转数组
        /// </summary>
        /// <param name="ilePath">文件路径</param>
        public static byte[] FileContent(string filePath)
        {
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                try
                {
                    byte[] buffur = new byte[fs.Length];
                    fs.Read(buffur, 0, (int)fs.Length);
                    return buffur;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

        /// <summary>
        /// 检查是否为数字
        /// </summary>
        /// <param name="strValue">字符串</param>
        /// <returns>true,false</returns>
        public static bool CheckIsNum(string strValue)
        {
            return Regex.IsMatch(strValue, @"^[+-]?\d*[.]?\d*$");
        }

        public static DataTable Transtorm(DataTable dt)
        {
            foreach (DataRow dr in dt.Rows)
            {
                foreach (DataColumn dc in dt.Columns)
                {
                    if (dr[dc].ToString().Contains("E"))
                    {
                        try
                        {
                            double baseNum = float.Parse(dr[dc].ToString().Substring(0, dr[dc].ToString().IndexOf("E")));
                            double power = float.Parse(dr[dc].ToString().Substring(dr[dc].ToString().IndexOf("E") + 1));
                            double num = Math.Pow(10, power);
                            double recentNum = baseNum * num;
                            dr[dc] = Math.Round(recentNum, 5);
                        }
                        catch (Exception)
                        {
                            return dt;
                        }
                    }
                }
            }
            return dt;
        }
    }
}
